package io.renren.modules.dangan.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alicp.jetcache.Cache;
import com.alicp.jetcache.anno.CacheType;
import com.alicp.jetcache.anno.CreateCache;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lowagie.text.DocumentException;
import io.renren.common.utils.Constant;
import io.renren.common.utils.PageUtils;
import io.renren.commons.dynamic.datasource.annotation.DataSource;
import io.renren.modules.dangan.dao.DaJnmlbDao;
import io.renren.modules.dangan.dao.DaOaWsDao;
import io.renren.modules.dangan.dao.DaServerDao;
import io.renren.modules.dangan.entity.DaJnmlbEntity;
import io.renren.modules.dangan.entity.DaOaWsEntity;
import io.renren.modules.dangan.entity.DaServerEntity;
import io.renren.modules.dangan.service.DaOaWsService;
import io.renren.modules.dangan.utils.FileUtils;
import io.renren.modules.dangan.utils.FtpUtils;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.shiro.ShiroUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.security.auth.Subject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static io.renren.modules.dangan.utils.DanganConstant.USERNAME;

/**
 * @auther guqianbin
 * @date 2019/8/5 21:42
 **/
@Service
@Slf4j
public class FileServiceImpl {
    @Autowired
    private DaJnmlbDao daJnmlbDao;

    @Autowired
    private DaServerDao daServerDao;

    @Autowired
    private DaOaWsDao daOaWsDao;

    @Autowired
    private DaOaWsServiceImpl daOaWsService;
    @Value("${upload.tempPath}")
    private String uploadTempPath;
    @CreateCache(name = "tempFile", cacheType = CacheType.LOCAL, localExpire = 1800, localLimit = 100)
    private Cache<String, String> uploadFileTemp;

    public void getFile(String jnmlbh, HttpServletResponse response, HttpServletRequest request) throws IOException {
        List<DaJnmlbEntity> daJnmlbEntities = daJnmlbDao.selectList(new QueryWrapper<DaJnmlbEntity>().eq("jnmlbh", Integer.parseInt(jnmlbh)));
        if (CollectionUtils.isEmpty(daJnmlbEntities)) {
            log.error("下载的文档不存在卷内目录:{}", jnmlbh);
        }
        DaJnmlbEntity daJnmlbEntity = daJnmlbEntities.get(0);
        DaServerEntity daServerEntity = daServerDao.selectById(daJnmlbEntity.getServerxh());
        String filePath = FileUtils.buildFilePath(daServerEntity, daJnmlbEntity);
        File file = new File(filePath);
//        File file = new File("/Users/guqianbin/Desktop/doc0605/Batch062/00000001.TIF");
//        File file = new File("/Users/guqianbin/Desktop/E.pdf");
//        File file = new File("D:\\00000001.tif");
        File pdfFile = new File(FileUtils.tifPath2PdfPath(file.getAbsolutePath()));

        //如果是tif 判断下是否存在pdf
        if (FileUtils.isTifFile(file) && !FileUtil.exist(pdfFile)) {
            pdfFile = FileUtils.tifToPdf(file);
        }
        try {
            SysUserEntity user = (SysUserEntity) ShiroUtils.getSubject().getPrincipal();
            pdfFile = FileUtils.setWatermark(pdfFile, user.getUsername());
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        FileUtils.writerFile(response, pdfFile);

    }

    public void getOaWsFile(Integer vrecid, HttpServletResponse response) throws IOException {
        log.info("查看oa的文书档案vrecid:{}", vrecid);
        Map<String,Object> params=new HashedMap();
        params.put("vrecid",vrecid);
        PageUtils page =daOaWsService.queryPage(params);
        if(page.getList().size()<=0){
            return;
        }
        DaOaWsEntity daOaWsEntity= (DaOaWsEntity) page.getList().get(0);
        DaServerEntity daServerEntity=daServerDao.selectById(daOaWsEntity.getServerxh());
        String lj=daOaWsEntity.getLj();
        String srcPath=lj.substring(0,lj.lastIndexOf("/")+1);
        String srcFileName=lj.substring(lj.lastIndexOf("/")+1,lj.length());
        String destFilePath = uploadTempPath
                + FileUtils.getFilePath()+daOaWsEntity.getVrecid()+"/"
                + srcFileName;
        FtpUtils.downloadOaFileFromFtp(daServerEntity,srcPath,srcFileName,destFilePath,srcFileName);
        File tifFile=new File(destFilePath);
        File pdfFile = new File(FileUtils.tifPath2PdfPath(tifFile.getAbsolutePath()));

        //如果是tif 判断下是否存在pdf
        if (FileUtils.isTifFile(tifFile) && !FileUtil.exist(pdfFile)) {
            pdfFile = FileUtils.tifToPdf(tifFile);
        }
        try {
            SysUserEntity user = (SysUserEntity) ShiroUtils.getSubject().getPrincipal();
            pdfFile = FileUtils.setWatermark(pdfFile, user.getUsername());
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        FileUtils.writerFile(response, pdfFile);
    }

    public void getFileByPath(String fileUUID, HttpServletResponse response) throws IOException {
        String filePath = uploadFileTemp.get(fileUUID);
        File file = new File(filePath);
        if (!file.exists()) {
            return;
        }
        File pdfFile = new File(FileUtils.tifPath2PdfPath(file.getAbsolutePath()));
        //如果是tif 判断下是否存在pdf
        if (FileUtils.isTifFile(file) && !FileUtil.exist(pdfFile)) {
            pdfFile = FileUtils.tifToPdf(file);
        }
        try {
            SysUserEntity user = (SysUserEntity) ShiroUtils.getSubject().getPrincipal();
            pdfFile = FileUtils.setWatermark(pdfFile, "ceshi");
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        FileUtils.writerFile(response, pdfFile);
    }

    /**
     * 返回服务器上临时路径
     *
     * @param multipartFile
     * @return
     */
    public String uploadFile(MultipartFile multipartFile) {
        BufferedOutputStream bufferedOutputStream = null;
        File targetFile = new File(uploadTempPath + multipartFile.getOriginalFilename());
        try {
            if (!targetFile.getParentFile().exists()) {
                targetFile.getParentFile().mkdirs();
            }
            multipartFile.transferTo(targetFile);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return targetFile.getAbsolutePath();
    }

}
